//
//  Style12ViewController.m
//  PiPiPineapple
//
//  Created by 李晓东 on 17/11/7.
//  Copyright © 2017年 PeanutXu. All rights reserved.
//

#import "Style12ViewController.h"
#import "DoubleChromosphere_Extension.h"
#import "Style12TableViewDataSource.h"
#import "SQLiteManager.h"
#import "ThroadToServer.h"
#import "Tools.h"

#import <Masonry.h>

@interface Style12ViewController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) Style12TableViewDataSource *dataSource;


@property (nonatomic, strong) NSMutableArray *array;
@property (nonatomic, strong) UIActivityIndicatorView *indicatorView;
@end

//#define CRow 20

@implementation Style12ViewController

- (void)loadView{
    [super loadView];
    self.tableView = [[UITableView alloc]init];
    [self.view addSubview:self.tableView];
    
    self.array = [NSMutableArray array];
    self.dataSource = [[Style12TableViewDataSource alloc]initWithData:self.array];
    
    [self loadFromDataBase:nil andCount:CRow andParameter:nil andOperate:nil andOrder:@"expect"];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.tableView.dataSource = _dataSource;
    self.tableView.delegate = self;
    
    UINib *nib = [UINib nibWithNibName:@"Style12TableViewCell" bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:@"li"];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view.mas_top);
        make.left.mas_equalTo(self.view.mas_left);
        make.width.mas_equalTo(self.view.mas_width);
        make.height.mas_equalTo(self.view.mas_height);
    }];
    
    // 上拉 UI
    _indicatorView = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    [_indicatorView setColor:[UIColor redColor]];
    self.tableView.tableFooterView = _indicatorView;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (self.tableView.contentOffset.y + scrollView.frame.size.height > scrollView.contentSize.height + 40 && ![_indicatorView isAnimating] ) {
        [_indicatorView startAnimating];
        
        DoubleChromosphere *obj = (DoubleChromosphere *)_array.lastObject;
        [self loadFromDataBase:obj.returnIssueno andCount:CRow andParameter:@"expect" andOperate:@" < " andOrder:@"expect"];
    }
    
}

/**
 从数据库中加载数据

 @param issueno <#issueno description#>
 @param count <#count description#>
 @param order <#order description#>
 */
- (void)loadFromDataBase:(NSString *)issueno andCount:(NSInteger)count andParameter:(NSString *)param andOperate:(NSString *)operate andOrder:(NSString *)order {
    
    // 第一次进入到这个 UI, 会先从数据库加载数据.当发现没有数据时,会向网络请求(获取多条记录).返回的结果集会被记录到数据库,以及加载 array, 并刷新 tableViewcell; 但当数据库有数据时,也会向网络请求(获取一条最新记录),然后和数据库最新的记录比较,记录下相差的期数diff.如果diff=0,则数据库有最新的,放弃这条记录,把记过加载到 array, 并刷新 tableView;否则则保存这条记录,再判断是否大于1.大于1的话,就在访问网络(获取多条记录),把再访问网络返回的记录加载刚才的查询结果中,再把值加载给 array 和记录到数据库,再刷新 tableView;
    
    // 再完成第一次加载后.上拉刷新时,需要取出当前 tableView中最后一条记录.以该记录为条件,先从数据库加载数据.如果数据库中没有记录,则以刚才去到的记录的期数为条件,向网络请求(获取多条记录),返回的结果记录到数据库,以及加载 array, 并刷新 tableView.如果数据库中有记录,则把返回的记录加载到 array 中,并判断返回的记录数是否达到 CRow 条.如果没有达到,则向网络请求(获取多条记录),返回结果集会记录到数据库,以及加载 array, 并刷新 tableVIewCell .如果已经达到,则只刷新 tableViewcell
    
    
    RetuenBlock returnBlock = ^(NSArray *array1, BOOL needRefresh){
        // 1.1如果存在,就从中加载,并判断是否是最新的期数
        if (array1.count == 0) {
            [array1 arrayByAddingObjectsFromArray:[[[ThroadToServer shareThroadToServer]initWithParams:^(NSArray *array){
                [self insertData:array needInsertDataBase:YES haveIndexSet:-1];
                
                
            }] loadDoubleChromospheresByIssueno:issueno andRows:CRow]];
        } else if (array1.count < CRow) {
            [self.array addObjectsFromArray:array1];
            
            DoubleChromosphere *dbLastestObj = (DoubleChromosphere *)array1.firstObject;
            // array返回的是网络最新的一条记录
            [[[ThroadToServer shareThroadToServer]initWithParams:^(NSArray *array2){
                DoubleChromosphere *lastestObj = (DoubleChromosphere *)array2.lastObject;
                NSInteger diff = [lastestObj.returnIssueno integerValue] - [dbLastestObj.returnIssueno integerValue];
                if (diff > 0) {
                    [self.array insertObject:lastestObj atIndex:0];
                    
                    NSMutableDictionary *lastestDict = [NSMutableDictionary dictionary];
                    [lastestDict addEntriesFromDictionary:[lastestObj dictionaryWithValuesForKeys:@[@"redA", @"redB", @"redC", @"redD", @"redE", @"redF", @"blue"]]];
                    
                    lastestDict[@"opentime"] = lastestObj.returnOpendate;
                    lastestDict[@"expect"] = lastestObj.returnIssueno;
                    [[SQLiteManager share]insertDataOfArray:nil orDictionary:lastestDict inTable:@"T_DoubleChromosphere"];
                    
                    [[[ThroadToServer shareThroadToServer]initWithParams:^(NSArray *array3){
                        [self insertData:array3 needInsertDataBase:YES haveIndexSet:1];
                        
                    }] loadDoubleChromospheresByIssueno:lastestObj.returnIssueno andRows:diff - 1];

                } else {
                    
                    [self.tableView reloadData];

                }
            }] loadDoubleChromosphereByIssueno:nil];
   
        } else {
            [self insertData:array1 needInsertDataBase:NO haveIndexSet:-1];
 
        }
        

    };
    
    [[SQLiteManager share]queryDataInTable:@"T_DoubleChromosphere" andReturnBlock:returnBlock andOrderBy:order andSort:@"desc" andResultCount:CRow withParameter:param andOperate:operate andValue:issueno, nil];

}

- (void)insertData:(NSArray *)array needInsertDataBase:(BOOL)flag haveIndexSet:(NSInteger)indexOfIndexSet {
    
    dispatch_async(dispatch_get_main_queue(), ^{
        if (array != nil) {
            if (!flag) {
                [self.array addObjectsFromArray:array];
                
            } else {
                NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(indexOfIndexSet < 0 ? self.array.count : indexOfIndexSet, array.count)] ;
                [self.array insertObjects:array atIndexes:indexSet];
                [[SQLiteManager share]insertDataOfArray:array orDictionary:nil inTable:@"T_DoubleChromosphere"];
                
            }
            
            dispatch_sync(dispatch_get_global_queue(0, 0), ^{
                NSArray *acArray = [[Tools shareTools]type13:array];
                for (NSInteger i = acArray.count; i > 1; i--) {
                    NSArray *allRedArray = ((DoubleChromosphere *)acArray[i - 2]).returnRedBall;
                    NSString *allSomeStr = ((DoubleChromosphere *)acArray[i - 1]).returnSomebody;
                    if ([allRedArray containsObject:allSomeStr]) {
                        [((DoubleChromosphere *)acArray[i - 2]) setNextSomeBody:allSomeStr];
                        
                    }
                    
                }
            });
            
        }
        [self.indicatorView stopAnimating];
        [self.tableView reloadData];
    });
    
}
@end
